﻿using LiteBlog.Common.Entities;
using LiteBlog.Components.Contracts;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace LiteBlog.Components
{
    public class DocumentComp : IDocumentComp
    {
        public DocumentComp(IConfigComp configComp)
        {
            _configComp = configComp;
        }

        private IConfigComp _configComp;
        public IConfigComp ConfigComponent
        {
            get
            {
                return _configComp;
            }
        }

        public Document GetNew(string id)
        {
            var docPath = ConfigComponent.DocumentPath;

            string fileName = Path.GetFileName(id);
            string docName = Path.GetFileNameWithoutExtension(fileName);
            string extn = Path.GetExtension(fileName);

            string uploadPath = string.Format("{0}\\{1}", docPath, fileName);

            if (File.Exists(uploadPath))
            {
                int index = 0;
                do
                {
                    index++;
                    fileName = string.Format("{0}-{1}{2}", docName, index, extn);
                    uploadPath = string.Format("{0}\\{1}", docPath, fileName);
                }
                while (File.Exists(uploadPath));
            }

            var document = new Document();
            document.PhysicalPath = uploadPath;
            document.VirtualPath = string.Format("{0}/{1}", ConfigComponent.DocumentVirtualPath, fileName);
            return document;
        }

        public bool Remove(string id)
        {
            var path = Path.Combine(ConfigComponent.DocumentPath, id);
            bool remove = File.Exists(path);
            if (remove)
                File.Delete(path);
            return remove;
        }

        public bool Clone(string id)
        {
            throw new NotImplementedException();
        }
    }
}
